package com.lalifa.googledate.util

import android.annotation.SuppressLint
import android.content.ContentResolver.*
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.graphics.Color
import android.net.Uri
import android.provider.CalendarContract
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.LogUtils
import com.lalifa.extension.PATTERN_DATE
import com.lalifa.extension.pk
import com.lalifa.extension.toTime
import com.lalifa.extension.toast
import com.lalifa.googledate.R
import com.lalifa.googledate.api.CalendarBean
import com.lalifa.googledate.api.CountryListBean
import com.lalifa.googledate.api.EventInfo
import com.lalifa.googledate.api.EventListBean
import com.lalifa.googledate.api.HolidayShowBean
import com.lalifa.googledate.util.UserManager.Companion.get
import com.lalifa.utils.GsonUtil
import com.lalifa.utils.SPUtil
import org.joda.time.DateTimeZone
import org.joda.time.Days
import org.joda.time.Instant
import org.joda.time.LocalDate
import org.joda.time.LocalDateTime
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.Calendar
import java.util.TimeZone


object CalendarUtils {
    var CALENDARS_LIST = arrayListOf<CalendarBean>()
    var ACTIVITY_SHOW = false

    //当前日历生日
    var BIRTHDAY_Id = -1
    var BIRTHDAY_NAME = "addressbook#contacts@group.v.calendar.google.com"
    var BIRTHDAY_SHOW = false

    //当前日历id
    var CALENDARS_Id = -1L

    //当前日历名称
    var CALENDARS_NAME = "primary"

    //显示 public default
    var show = 1

    //
    //隐藏
    var hide = 0
    private var localDateHashMap = arrayListOf<EventListBean>()

    @SuppressLint("Range")
    fun getCalendar(context: Context, isOpenHoliday: Boolean): ArrayList<EventListBean>? {
        localDateHashMap = arrayListOf()
        val userCursor = context.contentResolver.query(
            CalendarContract.Calendars.CONTENT_URI,
            null, null, null, null
        )
        try {
            if (isOpenHoliday) {
                readWorldAreaCode(context)
            }
            if (userCursor == null || get() == null) { //查询返回空值
                return localDateHashMap
            }
            ACTIVITY_SHOW = false
            BIRTHDAY_Id = -1
            CALENDARS_Id = -1
            CALENDARS_LIST.clear()
            while (userCursor.moveToNext()) {
                val vis =
                    userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars.VISIBLE))
                val id =
                    userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars._ID))
                val name = userCursor.getString(2)
                  LogUtils.i("======日历>$name")
                if (get() != null) {
                    if (name == BIRTHDAY_NAME) {
                        BIRTHDAY_Id = id
                        if (vis == show) {
                            BIRTHDAY_SHOW = true
                        }
                    }
                    if (name == CALENDARS_NAME) {
                        if (vis == show) {
                            ACTIVITY_SHOW = true
                        }
                        CALENDARS_Id = id.toLong()
                    }
                    if (name.contains("diy#")) {
                        val account =
                            userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.ACCOUNT_NAME))
                        val color =
                            userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_COLOR))
                        val icon =
                            userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME))
                        val bean =
                            CalendarBean(id.toLong(), name.split("#")[1], account, color, icon)
                        CALENDARS_LIST.add(bean)
                    }
                    if (name != "local account" && vis == show && !name.contains("#holiday")) {
                        val selection = CalendarContract.Calendars.OWNER_ACCOUNT
                        getEvent(context, selection, name)
                    }
                }
            }
            return localDateHashMap
        } finally {
            userCursor?.close()
        }
    }

    /**
     * 读取世界各国节假日
     */
    private fun readWorldAreaCode(context: Context) {
        var br: BufferedReader? = null
        val sp = SPUtil.getSp(Tool.holidayName, Tool.holidayNameJson)
        val countryList = GsonUtil.json2Obj(sp, CountryListBean::class.java)
        countryList.countryList.forEach { country ->
            if (country.isPublic == 1) {
                try {
                    br = BufferedReader(
                        InputStreamReader(
                            context.resources.assets.open(country.name + ".json")
                        )
                    )
                    var line: String? = null
                    val sb = StringBuilder()
                    while (br!!.readLine().also { line = it } != null) {
                        sb.append(line)
                    }
                    br!!.close()
                    val json = sb.toString()
                    val codeList = GsonUtil.json2Obj(json.trim(), HolidayShowBean::class.java)
                    val items = codeList.items
                    items.forEach { ho ->
                        val startTime = ho.start.date.toTime(PATTERN_DATE)
                        val endTime = ho.start.date.toTime(PATTERN_DATE)
                        val timezone = codeList.timeZone
                        val eventInfo = EventInfo()
                        eventInfo.starttime = startTime
                        eventInfo.endtime = endTime
                        eventInfo.accountname = "holiday"
                        eventInfo.info = ho.organizer.displayName.pk()
                        eventInfo.timezone = timezone.pk()
                        eventInfo.isallday = true
                        eventInfo.eventtitles = arrayOf(ho.summary)
                        eventInfo.title = ho.summary.pk()
                        eventInfo.eventcolor = -2
                        eventInfo.title = ""
                        eventInfo.noofdayevent = 2
                        val localDate = getDate(startTime)
                        localDateHashMap.add(EventListBean(localDate, eventInfo))
                    }
                } catch (e1: Exception) {
                    LogUtils.i(e1.toString())
                } finally {
                    br?.close()
                }
            }
        }
    }

    @SuppressLint("Range", "Recycle")
    private fun getEvent(context: Context, key: String, value: String) {
        //  delCalendarAccount(context,9)
        val minTime = LocalDate().minusYears(Tool.minusYears)
        val maxTime = LocalDate().plusYears(Tool.plusYears)
        val selection = "(($key=?)AND(${CalendarContract.Events.DTSTART}>=" +
                "${minTime.toDateTimeAtStartOfDay().millis})AND(${CalendarContract.Events.DTEND}<=" +
                "${maxTime.toDateTimeAtStartOfDay().millis}))"
        val selectionArgs = arrayOf(value)
        val cursor = context.contentResolver.query(
            CalendarContract.Events.CONTENT_URI,
            null, selection, selectionArgs, null
        )
        if (cursor != null && cursor.count > 0) {
            while (cursor.moveToNext()) {
                val status =
                    cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DELETED))
                val id = cursor.getString(cursor.getColumnIndex("_id")).toInt()
                val eventTitle = cursor.getString(cursor.getColumnIndex("title"))
                val startTime = cursor.getString(cursor.getColumnIndex("dtstart")).toLong()
                val endTime = cursor.getString(cursor.getColumnIndex("dtend")).toLong()
                val duration =
                    cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DURATION))
                val timezone =
                    cursor.getString(cursor.getColumnIndex(CalendarContract.Events.EVENT_TIMEZONE))
                val allDay =
                    cursor.getString(cursor.getColumnIndex(CalendarContract.Events.ALL_DAY)).toInt()
                val color =
                    cursor.getInt(cursor.getColumnIndex(CalendarContract.Events.EVENT_COLOR))
                val address =
                    cursor.getString(cursor.getColumnIndex(CalendarContract.Events.EVENT_LOCATION))
                val accountId =
                    cursor.getString(cursor.getColumnIndex(CalendarContract.Events.CALENDAR_ID))
                if (status == "1") {
                    // LogUtils.i("====>$eventTitle")
                } else {
                    val eventInfo = EventInfo()
                    eventInfo.id = id
                    eventInfo.starttime = startTime
                    eventInfo.endtime = endTime
                    if (duration != null) {
                        eventInfo.endtime =
                            eventInfo.starttime + RFC2445ToMilliseconds(duration)
                    }
                    eventInfo.accountname = if (value.contains("holiday")) "节假日" else value
                    eventInfo.info =
                        cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DESCRIPTION))
                    eventInfo.timezone = timezone
                    eventInfo.eventtitles = arrayOf(eventTitle)
                    eventInfo.isallday = allDay == 1
                    eventInfo.title = eventTitle
                    eventInfo.address = address
                    eventInfo.accountId = accountId.toLong()
                    eventInfo.eventcolor =
                        if (color == 0) Color.parseColor(Tool.color) else color
                    val difference = eventInfo.endtime - eventInfo.starttime
                    if (difference > 86400000) {
                        if (allDay == 0) {
                            eventInfo.endtime = eventInfo.endtime + 86400000L
                        }
                        val localDate1 = LocalDateTime(
                            eventInfo.starttime,
                            DateTimeZone.forID(eventInfo.timezone)
                        ).withTime(0, 0, 0, 0)
                        val localDate2 =
                            LocalDateTime(eventInfo.endtime, DateTimeZone.forID(eventInfo.timezone))
                                .withTime(23, 59, 59, 999)
                        eventInfo.noofdayevent = Days.daysBetween(localDate1, localDate2).days
                        eventInfo.isallday = true
                    } else if (difference < 86400000) eventInfo.noofdayevent =
                        0 else eventInfo.noofdayevent = 1
                    val localDate = getDate(startTime)
                    localDateHashMap.add(EventListBean(localDate, eventInfo))
                }
            }
        }
    }

    /**
     * 添加日历事件
     *
     * @param title 事件标题 ""
     * @param description 事件描述 ""
     * @param location 事件地点 ""
     * @param startTime 开始时间 long
     * @param endTime 结束时间 long
     * @param isAllDay 是否全天 1-是 0-否
     * @param beforeTime 提前多久提醒  1 -1分钟
     * @param color 事件标记色 #000000
     */
    fun addCalendarEvent(
        context: Context?, title: String?, description: String?,
        location: String?, color: Int,
        startTime: Long, endTime: Long, isAllDay: String?,
        beforeTime: ArrayList<Int>, id: Long,
    ): Boolean {
        if (context == null) {
            return false
        }
        //添加日历事件
        val mCalendar = Calendar.getInstance()
        mCalendar.timeInMillis = startTime //设置开始时间
        val start = mCalendar.time.time
        mCalendar.timeInMillis = endTime //设置终止时间
        val end = mCalendar.time.time
        val event = ContentValues()
        event.put("title", title)
        event.put("description", description)
        if (id == -1L) {
            context.toast(context.getString(R.string.account_error))
            return false
        }
        event.put("calendar_id", id) //插入账户的id
        event.put(CalendarContract.Events.EVENT_COLOR, color)
        event.put(CalendarContract.Events.EVENT_LOCATION, location)
        event.put(CalendarContract.Events.ALL_DAY, isAllDay)
        event.put(CalendarContract.Events.DTSTART, start)
        event.put(CalendarContract.Events.DTEND, end)
        event.put(CalendarContract.Events.HAS_ALARM, 1) //设置有闹钟提醒
      //  event.put(CalendarContract.Events.EVENT_TIMEZONE, "UTC") //这个是时区，必须有
        event.put(CalendarContract.Events.EVENT_TIMEZONE, "Asia/Shanghai");//这个是时区，必须有
        val uri1: Uri = CalendarContract.Events.CONTENT_URI
        val newEvent = context.contentResolver.insert(uri1, event) ?: return false
        //事件提醒的设定
        val values = ContentValues()
        values.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(newEvent))
        values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT)
//        if (beforeTime.isNotEmpty()) {
//            beforeTime.forEach(Consumer { integer: Int? ->
//                values.put(CalendarContract.Reminders.MINUTES, integer) // 提前多少分钟有提醒
//            })
//        }
        values.put(CalendarContract.Reminders.MINUTES, 5) // 提前多少分钟有提醒
        val uri = context.contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, values)
        //添加事件提醒失败直接返回
        return uri != null
    }

    /**
     * 修改日历事件
     */
    fun Context.upEvent(
        eventID: Long,
        title: String?, description: String?,
        location: String?, color: Int,
        startTime: Long, endTime: Long, isAllDay: String?,
        beforeTime: ArrayList<Int>, id: Long,
        callback: (Boolean) -> Unit
    ) {
        val mCalendar = Calendar.getInstance()
        mCalendar.timeInMillis = startTime //设置开始时间
        val start = mCalendar.time.time
        mCalendar.timeInMillis = endTime //设置终止时间
        val end = mCalendar.time.time
        val values = ContentValues().apply {
            put(CalendarContract.Events.TITLE, title)
            put(CalendarContract.Events.DESCRIPTION, description)
            put(CalendarContract.Events.EVENT_LOCATION, location)
            put(CalendarContract.Events.EVENT_COLOR, color)
            put(CalendarContract.Events.DTSTART, start)
            put(CalendarContract.Events.DTEND, end)
            put(CalendarContract.Events.ALL_DAY, isAllDay)
            put(CalendarContract.Events.CALENDAR_ID, id)
        }
        val updateUri: Uri =
            ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID)
        val rows: Int = contentResolver.update(updateUri, values, null, null)
        callback(rows == 1)
    }

    fun changeCalendarSet(context: Context, type: Int, isShow: Boolean, callback: () -> Unit) {
        val values = ContentValues().apply {
            val i = if (isShow) show else hide
            put(CalendarContract.Calendars.VISIBLE, i)
        }
        when (type) {
            1 -> {
                for (i in CALENDARS_LIST) {
                    val updateUri: Uri = ContentUris.withAppendedId(
                        CalendarContract.Calendars.CONTENT_URI, i.id
                    )
                    context.contentResolver.update(updateUri, values, null, null)
                }
                val updateUri: Uri = ContentUris.withAppendedId(
                    CalendarContract.Calendars.CONTENT_URI, CALENDARS_Id
                )
                val i = context.contentResolver.update(updateUri, values, null, null)
                if (i == 1) {
                    callback()
                }
            }

            2 -> {
                val updateUri: Uri = ContentUris.withAppendedId(
                    CalendarContract.Calendars.CONTENT_URI, CALENDARS_Id.toLong()
                )
                val i = context.contentResolver.update(updateUri, values, null, null)
                if (i == 1) {
                    callback()
                }

            }

            3 -> {
                val updateUri: Uri = ContentUris.withAppendedId(
                    CalendarContract.Calendars.CONTENT_URI, BIRTHDAY_Id.toLong()
                )
                val i = context.contentResolver.update(updateUri, values, null, null)
                if (i == 1) {
                    callback()
                }
            }

            else -> {
                callback()
            }
        }
    }

    @SuppressLint("Range")
    fun upCalendarList(context: Context) {
        val userCursor = context.contentResolver.query(
            CalendarContract.Calendars.CONTENT_URI,
            null, null, null, null
        )
        userCursor.use { userCursor ->
            if (userCursor == null) { //查询返回空值
                return
            }
            CALENDARS_LIST.clear()
            while (userCursor.moveToNext()) {
                val id =
                    userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars._ID))
                val name = userCursor.getString(2)
                if (get() != null) {
                    if (name.contains("diy#")) {
                        val account =
                            userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.ACCOUNT_NAME))
                        val color =
                            userCursor.getInt(
                                userCursor.getColumnIndex(
                                    CalendarContract.Calendars.CALENDAR_COLOR
                                )
                            )
                        val icon =
                            userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME))
                        val bean =
                            CalendarBean(id.toLong(), name.split("#")[1], account, color, icon)
                        CALENDARS_LIST.add(bean)
                    }
                }
            }
        }
    }

    @SuppressLint("Range")
    private fun getReminder(context: Context) {
        val uri1: Uri = CalendarContract.Reminders.CONTENT_URI
        context.contentResolver.query(
            uri1,
            null, null, null, null
        ).use { cursor ->
            while (cursor!!.moveToNext()) {
                val EVENT_ID =
                    cursor.getLong(cursor.getColumnIndex(CalendarContract.Reminders.EVENT_ID))
                getEvent(context, CalendarContract.Events._ID, EVENT_ID.toString())
            }
            cursor.close()
        }
    }

    /**
     * 检查是否已经添加了日历账户，如果没有添加先添加一个日历账户再查询
     * 获取账户成功返回账户id，否则返回-1
     */
    private fun checkAndAddCalendarAccount(context: Context): Int {
        val oldId = checkCalendarAccount(context)
        return if (oldId >= 0) {
            oldId
        } else {
            -1
        }
    }

    /**
     * 检查是否存在现有账户，存在则返回账户id，否则返回-1
     */
    @SuppressLint("Range")
    private fun checkCalendarAccount(context: Context): Int {
        val userCursor = context.contentResolver.query(
            CalendarContract.Calendars.CONTENT_URI,
            null, null, null, null
        )
        return try {
            if (userCursor == null) { //查询返回空值
                return -1
            }
            val count = userCursor.count
            if (count > 0) { //存在现有账户，取第一个账户的id返回
                userCursor.moveToFirst()
                userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars._ID))
            } else {
                -1
            }
        } finally {
            userCursor?.close()
        }
    }

    /**
     * 添加日历账户，账户创建成功则返回账户id，否则返回-1
     */
    fun addCalendarAccount(
        context: Context,
        name: String,
        color: Int,
        icon: String
    ): Long {
        val timeZone = TimeZone.getDefault()
        val value = ContentValues()
        value.put(CalendarContract.Calendars.OWNER_ACCOUNT, name)
        value.put(CalendarContract.Calendars.NAME, name)
        value.put(CalendarContract.Calendars.ACCOUNT_NAME, get()!!.email)
        value.put(CalendarContract.Calendars.ACCOUNT_TYPE, get()!!.type)
        value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, icon)
        value.put(CalendarContract.Calendars.VISIBLE, 1)
        value.put(CalendarContract.Calendars.CALENDAR_COLOR, color)
        value.put(
            CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
            CalendarContract.Calendars.CAL_ACCESS_OWNER
        )
        value.put(CalendarContract.Calendars.SYNC_EVENTS, 1)
        value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.id)

        value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0)
        val uri1: Uri = CalendarContract.Calendars.CONTENT_URI
        var calendarUri = uri1
        calendarUri = calendarUri.buildUpon()
            .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
            .appendQueryParameter(
                CalendarContract.Calendars.ACCOUNT_NAME,
                get()!!.email
            )
            .appendQueryParameter(
                CalendarContract.Calendars.ACCOUNT_TYPE,
                get()!!.type
            )
            .build()
        val result = context.contentResolver.insert(calendarUri, value)
        return if (result == null) -1 else ContentUris.parseId(result)
    }

    /**
     * 修改日历账户，成功则返回账户id，否则返回-1
     */
    fun changeCalendarAccount(
        context: Context, id: String?, name: String,
        account: String, color: Int, icon: String
    ): Int {
        val value = ContentValues()
        value.put(CalendarContract.Calendars.NAME, name)
//        value.put(CalendarContract.Calendars.ACCOUNT_NAME, get()!!.email)
        value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, icon)
        value.put(CalendarContract.Calendars.CALENDAR_COLOR, color)
        value.put(CalendarContract.Calendars.OWNER_ACCOUNT, account)
        val uri1: Uri = CalendarContract.Calendars.CONTENT_URI
        val selection = "((${CalendarContract.Calendars._ID}=?))"
        val selectionArgs = arrayOf(id.toString())
        return context.contentResolver.update(uri1, value, selection, selectionArgs)

    }

    /**
     * 删除日历账户，成功则返回1，否则返回-1
     */
    fun delCalendarAccount(context: Context, id: Long): Int {
        val value = ContentValues()
        value.put(CalendarContract.Calendars._ID, id)
        val uri1: Uri = CalendarContract.Calendars.CONTENT_URI
        val selection = "((${CalendarContract.Calendars._ID}=?))"
        val selectionArgs = arrayOf(id.toString())
        return context.contentResolver.delete(uri1, selection, selectionArgs)
    }


    /**
     * 添加生日
     */
    fun addBirthdayEvent(context: Context?): Boolean {
        if (context == null) {
            return false
        }
        //添加日历事件
        val mCalendar = Calendar.getInstance()
        mCalendar.timeInMillis = System.currentTimeMillis() //设置开始时间
        mCalendar.timeInMillis = System.currentTimeMillis() //设置终止时间
        val start = mCalendar.time.time
        val end = mCalendar.time.time
        val event = ContentValues()
        event.put("calendar_id", CALENDARS_Id) //插入账户的id
        event.put(CalendarContract.Events.RRULE, "FREQ=YEARLY")
        event.put(CalendarContract.Events.DTSTART, start)
        event.put(CalendarContract.Events.DTEND, end)
        event.put(CalendarContract.Events.HAS_ALARM, 1) //设置有闹钟提醒
        event.put(CalendarContract.Events.EVENT_TIMEZONE, "UTC") //这个是时区，必须有
        //event.put(CalendarContract.Events.EVENT_TIMEZONE, "Asia/Shanghai");//这个是时区，必须有
        val newEvent = context.contentResolver.insert(CalendarContract.Events.CONTENT_URI, event)
            ?: //添加日历事件失败直接返回
            return false //添加事件
        //事件提醒的设定
        val values = ContentValues()
        values.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(newEvent))
        values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT)
        val uri = context.contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, values)
        //添加事件提醒失败直接返回
        return uri != null
    }

    /**
     * 检查日历事件
     *
     * @param context
     * @param title
     */
    @SuppressLint("Range")
    fun checkCalendarEvent(
        context: Context?, title: String?,
        description: String?, startTime: Long, endTime: Long
    ): Boolean {
        if (context == null) {
            return false
        }
        val eventCursor = context.contentResolver.query(
            CalendarContract.Events.CONTENT_URI,
            null,
            null,
            null,
            null
        )
        try {
            if (eventCursor == null) { //查询返回空值
                return false
            }
            if (eventCursor.count > 0) {
                //遍历所有事件，找到title跟需要查询的title一样的项
                var eventTitle = ""
                var eventDescription = ""
                var eventStartTime: Long
                var eventEndTime: Long
                while (eventCursor.moveToNext()) {
                    eventTitle = eventCursor.getString(eventCursor.getColumnIndex("title"))
                    eventDescription =
                        eventCursor.getString(eventCursor.getColumnIndex("description"))
                    eventStartTime =
                        eventCursor.getString(eventCursor.getColumnIndex("dtstart")).toLong()
                    eventEndTime =
                        eventCursor.getString(eventCursor.getColumnIndex("dtend")).toLong()
                    if (title != null && title == eventTitle && description != null && description == eventDescription && startTime == eventStartTime && endTime == eventEndTime) {
                        return true
                    }
                }
            }
        } finally {
            eventCursor?.close()
        }
        return false
    }

    /**
     * 删除日历事件
     */
    @SuppressLint("Range")
    fun AppCompatActivity.deleteCalendarEvent(eventID: Long, callback: (Int) -> Unit) {
        val deleteUri: Uri =
            ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID)
        val rows: Int = contentResolver.delete(deleteUri, null, null)
        callback(rows)
    }

    fun getDate(milliSeconds: Long): LocalDate {
        val instantFromEpochMilli = Instant.ofEpochMilli(milliSeconds)
        return instantFromEpochMilli.toDateTime(DateTimeZone.getDefault()).toLocalDate()
    }

    fun RFC2445ToMilliseconds(str: String?): Long {
        require(!(str == null || str.isEmpty())) { "Null or empty RFC string" }
        var sign = 1
        var weeks = 0
        var days = 0
        var hours = 0
        var minutes = 0
        var seconds = 0
        val len = str.length
        var index = 0
        var c: Char
        c = str[0]
        if (c == '-') {
            sign = -1
            index++
        } else if (c == '+') index++
        if (len < index) return 0
        c = str[index]
        require(c == 'P') { "Duration.parse(str='$str') expected 'P' at index=$index" }
        index++
        c = str[index]
        if (c == 'T') index++
        var n = 0
        while (index < len) {
            c = str[index]
            if (c >= '0' && c <= '9') {
                n *= 10
                n += (c.code - '0'.code)
            } else if (c == 'W') {
                weeks = n
                n = 0
            } else if (c == 'H') {
                hours = n
                n = 0
            } else if (c == 'M') {
                minutes = n
                n = 0
            } else if (c == 'S') {
                seconds = n
                n = 0
            } else if (c == 'D') {
                days = n
                n = 0
            } else if (c == 'T') {
            } else throw IllegalArgumentException("Duration.parse(str='$str') unexpected char '$c' at index=$index")
            index++
        }
        val factor = (1000 * sign).toLong()
        return factor * (7 * 24 * 60 * 60 * weeks + 24 * 60 * 60 * days + 60 * 60 * hours + 60 * minutes
                + seconds)
    }

}